<template>
  <div class="form-linkman">
    <biz-form-remote-select
      ref="linkman"
      :field="field"
      :placeholder="placeholder || $t('common.form.placeHolder.linkman.pla1')"
      v-model="linkmanValue"
      :cleared="clearable"
      :remote-method="searchCustomerLinkman"
      @input="updateLinkman"
      value-key="id"
    >
      <div slot="option" slot-scope="{ option }">
        <div class="customer-linkman">
          <span class="label-name">
            <label>{{$t('common.form.preview.linkman.label1')}}：</label>
            <span>{{ option.name }}</span>
          </span>
          <span>
            <label>{{$t('common.form.preview.linkman.label2')}}：</label>
            <span>{{ option.phone }}</span>
          </span>
        </div>
      </div>
    </biz-form-remote-select>

    <el-button v-if="createdContactsPermission" type="plain-third" class="ml_12" @click="handleCreateContacts">{{ $t('common.base.create') }}</el-button>

    <!-- start 联系人弹窗 -->
    <edit-contact-dialog ref="editContactDialogRef" :customer="customerInfo" />
    <!-- end 联系人弹窗 -->
  </div>
</template>

<script>
// mixin
import FormMixin from '@src/component/form/mixin/form';
// api
import { getTaskCustomerLinkman } from '@src/api/TaskApi.ts';
// util
import { linkmanSelectConversion } from '@src/util/conversionFunctionUtil.ts';
import _ from 'lodash';

import EditContactDialog from '@src/modules/customer/view/operationDialog/EditContactDialog.vue'

export default {
  name: 'form-linkman',
  mixins: [FormMixin],
  props: {
    value: [String, Number, Array],
    source: {
      type: Array,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  components: {
    EditContactDialog
  },
  data() {
    return {
      linkmanValue: this.value || [],
      customerId: '',
      customerInfo: {}
    };
  },
  watch: {
    value: {
      handler(newValue) {
        if (!newValue) return;

        let linkmanValue = _.cloneDeep(newValue);

        this.linkmanValue = linkmanValue.map(item => {
          item.label = `${item?.name || ''} ${item?.phone || ''}`;
          return item;
        });
      },
      immediate: true,
    },
  },
  computed: {
    createdContactsPermission() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'));

      return initData?.auths?.LINKMAN_ADD > 0;
    }
  },
  mounted() {
    this.$eventBus.$on('task_create_or_edit.update_linkman', this.updateLinkman);
  },
  beforeDestroy() {
    this.$eventBus.$off('task_create_or_edit.update_linkman', this.updateLinkman);
  },
  methods: {
    /**
     * @description: 更新表单的值
     */
    updateLinkman(newValue) {
      let currentContacts = Array.isArray(newValue) ? newValue : [newValue];
      this.inputForValue(
        currentContacts.map(item => {
          return {
            id: item.id,
            name: item.name,
            phone: item.phone,
          };
        })
      );
    },
    // 获取客户id
    getCustomerId() {
      let field = this.fields.find(item => item.formType == 'customer' || item.formType === 'projectCustomer');

      let customerValue = (field && this.formValue?.[field.fieldName]) ?? [];

      if (customerValue?.length <= 0) {
        this.customerId = '';
        return this.$message.warning(this.$t('common.form.tip.chooseBeforeTips', {module:this.$t('common.base.customer')}));
      }

      this.customerInfo = customerValue?.[0];

      return this.customerId = Array.isArray(customerValue) ? customerValue?.[0]?.id : '';
    },
    /**
     * @description: 搜索联系人列表
     */
    async searchCustomerLinkman(params) {
      params.customerId = this.getCustomerId();

      // 没有客户id返回空
      if (!params.customerId) return [];

      return this.searchLinkman(params);
    },
    /**
     * @description: 搜索客户联系人
     */
    async searchLinkman(params = {}) {
      try {
        let data = await getTaskCustomerLinkman(params);

        let result = data.result;

        if (!result || !result.list) return;

        result.list = result.list.map(linkman =>
          linkmanSelectConversion(linkman)
        );
        return result;
      } catch (error) {
        console.warn('edit-form: searchProduct -> error', error);
      }
    },
    // 新建
    handleCreateContacts() {
      this.getCustomerId();

      if(!this.customerId.length) return;

      this.$refs.editContactDialogRef.openDialog();
    }
  },
};
</script>

<style lang="scss" scoped>
.form-linkman {
  display: flex;
  flex-flow: row nowrap;
}
.customer-linkman {
  display: flex;
  margin: 0;

  span {
    label {
      display: inline-block;
      width: auto;
      margin-bottom: 0;
    }

    span {
      margin-right: 10px;
    }
  }
  .label-name {
    max-width: 350px;
    @include text-ellipsis();
  }
}
::v-deep .el-input--small .el-input__inner {
  line-height: 0 !important;
}
</style>
